package models

import (
	"ahutoj/web/dao"
	mysqldao "ahutoj/web/dao/mysqlDao"
	"ahutoj/web/utils"
	"context"
	"errors"
	"gorm.io/gorm"
)

// 通过UID判断用户是否存在
func IsUserExistByUID(ctx context.Context, user *dao.User) bool {
	count, err := mysqldao.SelectUserCountByUID(ctx, user.UID)
	if err != nil {
		return false
	}
	return count > 0
}

func IsUserExistByEmail(ctx context.Context, user *dao.User) bool {
	count, err := mysqldao.SelectUserCountByEmail(ctx, user.Email)
	if err != nil {
		return false
	}
	return count > 0
}

func IsEmailExist(ctx context.Context,email string) bool {
	count,err := mysqldao.SelectEmail(ctx, email)
	if err != nil {
		return false
	}
	return count > 0
}


// func IsUserEmailExist(ctx context.Context,uid string,email string) bool {
// 	logger := utils.GetLogInstance()
// 	err := mysqldao.SelectUserEmail(ctx, uid,email)
// 	if err != nil {
// 		logger.Errorf("call SelectUserCountByUID failed, user=%+v, err=%s", utils.Sdump(email), err.Error())
// 		return false
// 	}
// 	return true
// }
// 通过UID获得用户信息
func FindUserByUID(ctx context.Context, user *dao.User) error {
	return mysqldao.SelectUserByUID(ctx, user)
}

func FindUserByEmail(ctx context.Context, user *dao.User) error {
	return mysqldao.SelectUserByEmail(ctx, user)
}

// 判断用户密码是否相同
func EqualPassWord(ctx context.Context, user *dao.User, password string) bool {
	md5Password, err := utils.MD5EnCode(user.UID, password)
	if err != nil {
		return false
	}
	return md5Password == user.Pass
}

func CreateUser(ctx context.Context, user *dao.User) error {
	logger := utils.GetLogInstance()
	// 2、密码加密处理（MD5)  字符串  --->  MD5序列
	user.Pass, _ = utils.MD5EnCode(user.UID, user.Pass)
	err := mysqldao.InsertUserTable(ctx, *user)
	if err != nil {
		logger.Errorf("call InsertUserTable failed,user= %+v, err=%s", utils.Sdump(user), err.Error())
	}
	return err
}

func GetUserList(ctx context.Context,token string,offset,limit int) ([]dao.User, error) {
	return mysqldao.SelectUserList(ctx,token,offset,limit)
}

func UpdateUserEmail(ctx context.Context, UID string, email string) error {
	return mysqldao.UpdateEmailByUID(ctx, UID, email)
}

func GetUserCount(ctx context.Context)int64{
	// logger := utils.GetLogInstance()
	count, err := mysqldao.SelectUserCount(ctx)
	if err != nil {
		// logger.Errorf("call SelectUserCountByUID failed, err=%s", err.Error())
		return 0
	}
	return count
}

func GetUserByQQ(ctx context.Context, QQ string) *dao.User {
	logger:=utils.GetLogInstance()
	user,err:=mysqldao.SelectUserByQQ(ctx, QQ)
	if errors.Is(err, gorm.ErrRecordNotFound){
		return nil
	}else if err!= nil {
		logger.Errorf("call SelectUserByQQ failed, QQ=%s, err=%s", QQ, err.Error())
		return nil
	}
	return user
}	

func UpdateUserQQ(ctx context.Context,user *dao.User) error {
	logger:=utils.GetLogInstance()
	err:=mysqldao.UpdateUserQQ(ctx, user)
	if err!= nil {
		logger.Errorf("call UpdateUserQQ failed, user=%+v, err=%s", utils.Sdump(user), err.Error())
	}
	return err
}	

